// pages/branch_manager/branch_manager.js
var app=getApp()
var selected_mid = []; //单灯统计数组

//日历用到的变量
const date = new Date()
const years = []
const months = []
const days = []

// for (let i = 1990; i <= date.getFullYear(); i++) {
//   years.push(i)
// }
for (let i = date.getFullYear(); i >= 2010; i--) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  var k = i;
  if (0 <= i && i <= 9) {
    k = "0" + (i);
  } else {
    k = (i);
  }
  months.push(k)
}

for (let i = 1; i <= 31; i++) {
  var k = i;
  if (0 <= i && i <= 9) {
    k = "0" + (i);
  } else {
    k = (i);
  }
  days.push(k)
}
//日历变量

var page = 0;
var page_size = 10
let header = {
  'content-type': 'application/x-www-form-urlencoded',
  'cookie': "openid=" + app.globalData.openid
}
var GetList = function (that, type) {
  that.setData({
    hidden: false
  });

  let url_str = ''
  if (that.data.currentIndex == 2) {
    url_str = 'https://119.3.46.145/server/GetDeviceStatusHistory'
  }

  if (that.data.currentIndex == 3) {
    url_str = 'https://119.3.46.145/server/GetAlarmHistory'
  }
  wx.request({
    //参数devNo: 868221043220329 start: 0 num: 20 startTime:2020-01-08 00:00:00 endTime:2020-01-08 23:59:59
    url: url_str,
    method: 'post',
    data: {
      userid: app.globalData.userid,
      devNo: parseInt(that.data.devNo),
      start: page_size * page,
      num: page_size,
      startTime: that.data.startTime,
      endTime: that.data.endTime,
    },
    header: header,
    success: function (res) {
      let data = JSON.parse(res.data.data);
      if (data.length == 0) {
        that.setData({
          hidden: true,
          // list:[]
        });
        return;
      }

      //tmp_list 再正常状态是需要push下一页，所以需要赋值是 that.data.list,
      var tmp_list = [];

      if (type != 'filter') {
        tmp_list = that.data.list;
      }

      for (var i = 0; i < data.length; i++) {
        tmp_list.push(data[i]);
      }
      that.setData({
        list: tmp_list,
        hidden: true
      });
      // console.log(that.data.list, 'that.data.list');
      page++;

    }
  });
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    hidden: true,
    list: [],
    scrollTop: 0,
    scrollHeight: 0,
    current_info: {},
    devNo: '',//当前分支的devNo   

    //日历变量
    DialogTitle: "日期",
    years: years,
    year: date.getFullYear(),
    months: months,
    month: 2,
    days: days,
    day: 2,
    value: [9999, 1, 1],
    // startTime: date.getFullYear()+'-01-01 00:00:00',
    // endTime: date.getFullYear()+'-01-01 23:59:59'
    startTime: '',
    endTime: '',
    date_array: [],
    lamp_type_array: [
      {
        id: "0",
        name: "普通灯"
      },
      {
        id: "1",
        name: "十字路口灯"
      },
      {
        id: "2",
        name: "主干道灯"
      },
      {
        id: "3",
        name: "人行道灯"
      },
      {
        id: "4",
        name: "隧道灯"
      }
    ] ,  


    loadgroupmid:'',
    loadgroupid:'',
    loadname:'',
    districtid:'',
    districtmid:'',
    districtname:'',
    branchid:'',//branch的id
    branchmid:'',//branch的mid
    branchname:'',
   
    branch_lamp_list:[], //分支下的灯

    cancel_all_selected: false,    
    selected_all: false,
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    that.setData({
      loadgroupmid: options.loadgroupmid,
      loadgroupid: options.loadgroupid,
      loadname: options.loadname,
      districtid: options.districtid,
      districtmid: options.districtmid,
      districtname: options.districtname,
      branchid: options.id,//branch的id
      branchmid: options.mid,//branch的mid
      branchname: options.branchname,
      devNo:options.devNo
    });

    //console.log(that.data, "that,data")  
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    wx.request({
      url: 'https://119.3.46.145/server/FindLightOnBranch?id=' + that.data.branchmid, //注意此处是mid和loadTree不一样 loadTree是id
      method: 'post',
      header: header,
      success: res => {
        //console.log(res, "res");
        //{"data":"[{\"LightType\":\"2\",\"LightNo\":\"23\",\"LightBrand\":\"1\",\"id\":\"20\",\"BranchID\":\"67\",\"Name\":\"灯2\"},{\"LightType\":\"0\",\"LightNo\":\"2\",\"LightBrand\":\"1\",\"id\":\"22\",\"BranchID\":\"67\",\"Name\":\"灯3\"}]"}
        
       
        let data = JSON.parse(res.data.data);

        if (data.length == 0) {
          return;
        }

        data.forEach(function(item, index, self){
          item.isSelect = false;
        });

        //console.log(data, "data loadgroup")
        let tmp_branch_lamp_list = [];        

        data.forEach(function (item, index, self) {
          item.isSelect = false;        
          tmp_branch_lamp_list.push(item);
        });

        that.setData({
          branch_lamp_list: tmp_branch_lamp_list         
        });
      },
      fail: error => {

      }
    });
  },

  selectedApply_all: function (e) {
    let that = this;
    
    let tmp_selected_all = that.data.selected_all;
    // let tmp_cancel_all_selected = that.data.cancel_all_selected;
    that.setData({
      selected_all: !tmp_selected_all,
      // cancel_all_selected: !tmp_cancel_all_selected
    });

    if (that.data.selected_all == true) {
      that.setData({
        cancel_all_selected: false
      });
    }

    let tmp_branch_lamp_list = that.data.branch_lamp_list;
    tmp_branch_lamp_list.forEach(function (item, index, self) {
      if (item.isSelect == false) {
        item.isSelect = true;
      }
    })

    that.setData({
      branch_lamp_list: tmp_branch_lamp_list
    });

    //先置空
    selected_mid = [];
    that.data.branch_lamp_list.forEach(function (item, index, self) {
      selected_mid.push(item.attributes.mid);
    });
  },

  cancel_selectedApply_all: function (e) {
    let that = this;
   
      let tmp_cancel_all_selected = that.data.cancel_all_selected;
      that.setData({
        cancel_all_selected: !tmp_cancel_all_selected
      });

      if (that.data.cancel_all_selected == true) {
        that.setData({
          selected_all: false
        });
      }

      let tmp_branch_lamp_list = that.data.branch_lamp_list;
      tmp_branch_lamp_list.forEach(function (item, index, self) {
        if (item.isSelect == true) {
          item.isSelect = false;
        }
      })

      that.setData({
        branch_lamp_list: tmp_branch_lamp_list
      });

      selected_mid = [];

  },

  del_branch_lamp: function () {
    let that = this;

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    if (that.data.currentIndex == 0) {
      if (selected_mid.length == 0) {
        wx.showModal({
          title: '提示',
          content: "暂无选中的设备",
          show_cancel: false
        });
        return;
      }

      wx.request({
        url: "https://119.3.46.145/server/DeleteLightOnBranch",
        type: "post",
        header:header,
        data: {
          id: selected_mid.join(',')
        },
        success: function (response) {
          let error = JSON.parse(response).error;
          if (error == -1){
            wx.showModal({
              title: '提示',
              content: '删除失败',
              showCancel:false
            })
          }            
          else if (error == 0) {
            wx.showModal({
              title: '提示',
              content: '删除成功',
              success:function(){
                wx.request({
                  url: 'https://119.3.46.145/server/FindLightOnBranch?id=' + that.data.branchmid, //注意此处是mid和loadTree不一样 loadTree是id
                  method: 'post',
                  header: header,
                  success: res => {
                    //console.log(res, "res");
                    //{"data":"[{\"LightType\":\"2\",\"LightNo\":\"23\",\"LightBrand\":\"1\",\"id\":\"20\",\"BranchID\":\"67\",\"Name\":\"灯2\"},{\"LightType\":\"0\",\"LightNo\":\"2\",\"LightBrand\":\"1\",\"id\":\"22\",\"BranchID\":\"67\",\"Name\":\"灯3\"}]"}


                    let data = JSON.parse(res.data.data);

                    if (data.length == 0) {
                      return;
                    }

                    data.forEach(function(item, index, self){
                      item.isSelect = false;
                    });

                    //console.log(data, "data loadgroup")
                    let tmp_branch_lamp_list = [];

                    data.forEach(function (item, index, self) {
                      item.isSelect = false;
                      tmp_branch_lamp_list.push(item);
                    });

                    that.setData({
                      branch_lamp_list: tmp_branch_lamp_list
                    });
                  },
                  fail: error => {

                  }
                });

              }
            })
           
          }
        }
      })
      
    }

   
  },


  add_branch_lamp: function () {
    let that = this;
    if (that.data.currentIndex == 0) {
      wx.navigateTo({
        url: '../new_branch_lamp/new_branch_lamp?loadgroupmid=' + that.data.loadgroupmid + '&loadgroupid=' + that.data.loadgroupid + '&loadname=' + that.data.loadname + '&districtid=' + that.data.districtid + '&districtmid=' + that.data.districtmid + '&districtname=' + that.data.districtname + '&branchmid=' + that.data.branchmid + '&branchid=' +that.data.branchid + '&branchname='+that.data.branchname
      })
    }

    // if (that.data.currentIndex == 1) {
    //   wx.navigateTo({
    //     url: '../new_branch/new_branch?loadgroupmid=' + that.data.loadgroupmid + '&loadgroupid=' + that.data.loadgroupid + '&loadname=' + that.data.loadname + '&districtid=' + that.data.districtid + '&districtmid=' + that.data.districtmid + '&districtname=' + that.data.districtname
    //   })
    // }
  },

  titleClick: function (e) {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    //页面变量全部重置
    this.setData({
      //拿到当前索引并动态改变
      currentIndex: e.currentTarget.dataset.idx
    });

    //状态与控制
    if(that.data.currentIndex == 1){
      that.refreshState();
     
    }

    if (e.currentTarget.dataset.idx == 2) {
      //充值起始页
      page = 0;
      that.setData({
        list: []
      });

      //请求状态与变更日志
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            scrollHeight: res.windowHeight
          });
        }
      });

      GetList(that);
    }

    if (e.currentTarget.dataset.idx == 3) {
      //重置起始页
      page = 0;

      that.setData({
        list:[]
      });     

      //请求告警日志
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            scrollHeight: res.windowHeight
          });
        }
      });

      GetList(that);
    }   

    
  },

  pagechange: function (e) {
    //console.log(e, "e");
    if ("touch" === e.detail.source) {
      let currentPageIndex = this.data.currentIndex
      currentPageIndex = (currentPageIndex + 1) % 2
      //console.log(currentPageIndex, "currentPageIndex");
      this.setData({
        currentIndex: currentPageIndex
      });
    }
  },

  selectApply: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let currentItem = that.data.currentIndex; //根据这个值判断 是swiper的那个部分
    //let  item = that.data.lamp_list[index];  
    let item = {};
    //单灯
    if (currentItem == 0) {
      item = that.data.branch_lamp_list[index];
    }
  
    let mid = e.currentTarget.dataset.mid;

    item.isSelect = !item.isSelect;


    
    if (currentItem == 0) {
      that.setData({
        branch_lamp_list: that.data.branch_lamp_list,
      });

      if (item.isSelect == true) {
        //判断在线列表中是否存在该设备，不在添加
        if (selected_mid.indexOf(mid) === -1) {
          selected_mid.push(mid);
        }
      }

      if (item.isSelect == false) {
        //判断不在线列表是否存在该设备,在就删除
        if (selected_mid.indexOf(mid) !== -1) {
          selected_mid.splice(selected_mid.indexOf(mid), 1);
        }
      }
    }
    
  },

//删除支路上的单个灯
  del_single_branch_lamp:function(e){
    //console.log(e, "e");
    let that = this;
   
    let id = e.currentTarget.dataset.id;

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    if (that.data.currentIndex == 0) {      
      wx.request({
        url: "https://119.3.46.145/server/DeleteLightOnBranch",
        type: "post",
        header: header,
        data: {
          id: id
        },
        success: function (response) {
          console.log(response, 'response');

          let error = response.data.error;
          if (error == -1) {
            wx.showModal({
              title: '提示',
              content: '删除失败',
              showCancel: false
            })
          }
          else if (error == 0) {
            wx.showModal({
              title: '提示',
              content: '删除成功',
              success: function () {
                wx.request({
                  url: 'https://119.3.46.145/server/FindLightOnBranch?id=' + that.data.branchmid, //注意此处是mid和loadTree不一样 loadTree是id
                  method: 'post',
                  header: header,
                  success: res => {
                    //console.log(res, "res");
                    //{"data":"[{\"LightType\":\"2\",\"LightNo\":\"23\",\"LightBrand\":\"1\",\"id\":\"20\",\"BranchID\":\"67\",\"Name\":\"灯2\"},{\"LightType\":\"0\",\"LightNo\":\"2\",\"LightBrand\":\"1\",\"id\":\"22\",\"BranchID\":\"67\",\"Name\":\"灯3\"}]"}


                    let data = JSON.parse(res.data.data);

                    if (data.length == 0) {
                      return;
                    }

                    data.forEach(function (item, index, self) {
                      item.isSelect = false;
                    });

                    //console.log(data, "data loadgroup")
                    let tmp_branch_lamp_list = [];

                    data.forEach(function (item, index, self) {
                      item.isSelect = false;
                      tmp_branch_lamp_list.push(item);
                    });

                    that.setData({
                      branch_lamp_list: tmp_branch_lamp_list
                    });
                  },
                  fail: error => {

                  }
                });

              }
            })

          }
        }
      })
    }
  },

  refreshState:function() {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
    
    wx.request({
      url: "https://119.3.46.145/server/GetLastInfo",
      data: {
        devNo: that.data.devNo
      },
      header:header,
      type: "post",
      success: function (response) {
        let data = JSON.parse(response.data.data);
        //console.log(data, "data");
        //{"data":"[{\"SecondTurnOffTime\":\"7:4:00\",\"Ver\":\"1.0.6\",\"devNo\":\"861428040106263\",\"Volt\":236.4,\"Latitude\":0.0,\"type\":\"2\",\"FirstTurnOnTime\":\"17:18:00\",\"DevCurrentTime\":\" 7:59:00\",\"Longitude\":0.0,\"FirstOrSumElec\":0.0,\"SecondTurnOnTime\":\"17:18:00\",\"Auto\":true,\"SIG\":\"非常好\",\"OnLine\":false,\"SecondElec\":0.0,\"FirstSwitch\":false,\"FirstTurnOffTime\":\"7:4:00\",\"SecondSwitch\":false,\"Interval\":0}]"}
        let current_info = {}
        if (data.length != 0) {
          that.setData({
            current_info: data[0]
          });
        }        
      }
    })
  },

  OPEN: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 0
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          // alert("已加入任务队列，等待执行");
          // refreshTask();
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  AUTO: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 2
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          // alert("已加入任务队列，等待执行");
          // refreshTask();
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  MANUAL: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 3
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  bindDownLoad: function () {
    var that = this;
    //console.log(page, "page");
    GetList(that);
  },

  scroll: function (event) {
    this.setData({
      scrollTop: event.detail.scrollTop
    });
  },

  refresh: function (event) {
    page = 0;
    this.setData({
      list: [],
      scrollTop: 0
    });
    GetList(this)
  },

  _text: function () {
    var that = this;
    that.calendar.showDialog();
  },

  //确定按钮的返回值
  _cancelEvent(e) {
    let that = this;
    this.calendar.hideDialog();
    if (that.data.currentIndex == 0) {
      return;
    }

    let array = that.data.date_array;

    let date_time = '';
    let year = '';
    let month = '';
    let day = '';
    year = years[array[0]];
    month = months[array[1]];
    day = days[array[2]];

    that.setData({
      startTime: year + '-' + month + '-' + day + " 00:00:00",
      endTime: year + '-' + month + '-' + day + " 23:59:59"
    });

    page = 0;//重置页面 page从0开始
    GetList(that, 'filter');
  },

  _cancelEvents(e) {
    let that = this;
    that.setData({
      date_array: e.detail
    });

    //console.log(e.detail, "e.detail");

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
    that.calendar = this.selectComponent("#calendar");

  },

  goto_task_queue: function () {
    wx.switchTab({
      url: '../task_queue/task_queue',
    })
  },

  goto_index: function () {
    wx.switchTab({
      url: '../index/index',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})